package cn.pda.scan;

import java.lang.ref.WeakReference;

import com.demo.scan.R;

import android.app.Service;
import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.util.Log;
import android.util.SparseIntArray;


/**
 * 音频播放管理器
 *
 * @author 79442
 * @date 2018/2/2
 */

public class SoundPoolMgr {

	private static SoundPoolMgr INSTANCE;
	private WeakReference<Context> mWeakReference;
	private SoundPool mSoundPool;
	/**
	 * 创建一个SparseIntArray对象,使用SparseIntArray管理各种音频
	 */
	private SparseIntArray mSoundMap = new SparseIntArray();

	/**
	 * 单例模式
	 */
	public static SoundPoolMgr getInstance(Context context) {
		if (INSTANCE == null) {
			INSTANCE = new SoundPoolMgr(context);
		}
		return INSTANCE;
	}

	private SoundPoolMgr(Context context) {
		mWeakReference = new WeakReference<>(context);
		SoundPool.Builder builder = new SoundPool.Builder();
		// 音频属性的Builder
		AudioAttributes.Builder attrBuild = new AudioAttributes.Builder();
		// 音频类型
		attrBuild.setLegacyStreamType(AudioManager.STREAM_SYSTEM);
		// 设置音频属性
		builder.setAudioAttributes(attrBuild.build());
		// 设置最大的同时播放音频流数
		builder.setMaxStreams(4);
		// 建立SoundPool
		mSoundPool = builder.build();
		// 加载音频
		load();
	}

	/**
	 * 加载音频文件存储在map中
	 */
	private void load() {
		try {
			// 把你的声音素材放到res/raw里
			mSoundMap.put(1, mSoundPool.load(mWeakReference.get(), R.raw.scan, 1));
			AudioManager audioManager = (AudioManager) mWeakReference.get().getSystemService(Service.AUDIO_SERVICE);
			if (audioManager == null){
				Log.e("Huang, SoundPoolMgr", "Get AudioManager returns null");
				return;
			}
			/*
			 * 设置媒体音量为最大音量
			 */
			int maxMusic = audioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);
			int curMusic = audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);
			Log.e("Huang, SoundPoolMgr.java", "music_max:" + maxMusic + ", cur:" + curMusic);
			audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM,maxMusic,AudioManager.FLAG_SHOW_UI);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Play a sound from a sound ID.
	 */
	public void play(int soundId) {
		/*
		 * @param soundID
		 *            通过load方法返回的音频
		 * @param leftVolume
		 *            左声道的音量(range = 0.0 to 1.0)
		 * @param rightVolume
		 *            右声道的音量(range = 0.0 to 1.0)
		 * @param priority
		 *            优先级，值越大，优先级越高(0 = lowest priority)
		 * @param loop
		 *            循环的次数：0为不循环，-1为无限循环
		 * @param rate
		 *            指定速率，正常位1，为地位0.5，最高位2
		 * @return non-zero streamID if successful, zero if failed
		 */
		int streamID = mSoundPool.play(mSoundMap.get(soundId), 1, 1, 10, 0, 1);
		android.util.Log.i("Huang, SoundPoolMgr.java", "play() return streamID: " + streamID);
	}

	/**
	 * 释放音频资源
	 */
	public void realease() {
		mSoundPool.autoPause();
		mSoundPool.unload(mSoundMap.get(1));
		mSoundPool.release();
		mSoundPool = null;
		INSTANCE = null;
		mSoundMap = null;
	}
}
